package net.yeah.mickey_zhouyou.util.fcs.elem;

import java.io.IOException;

import net.yeah.mickey_zhouyou.util.fcs.ReaderOverException;
import net.yeah.mickey_zhouyou.util.fcs.ReaderWrapper;
import net.yeah.mickey_zhouyou.util.fcs.SyntaxException;

public abstract class ConditionSelector extends Selector {

	public static ConditionSelector create(ReaderWrapper reader)
			throws IOException {
		try {
			char b = reader.readNotBlank();
			if (b == '(') {
				b = reader.lookNotBlank();

				ConditionSelector selector = null;

				if (b == '!') {
					reader.readNotBlank();
					selector = new ConditionNot(create(reader));
				} else if (b == '(') {
					selector = create(reader);
				} else if (b == ')') {
					throw new SyntaxException("条件选择器无法读取一个完整的条件",
							reader.getCurrentRow(), reader.getCurrentColumn());
				}

				if (selector == null) {
					selector = ConditionCompare.create(reader);
					b = reader.readNotBlank();
					if (b == ')')
						return selector;
					throw new SyntaxException("条件选择器无法读取一个完整的条件",
							reader.getCurrentRow(), reader.getCurrentColumn());
				}
				int ls = readcc(reader);
				if (ls == 1)
					selector = new ConditionAnd(selector, create(reader));
				else if (ls == 0)
					selector = new ConditionOr(selector, create(reader));
				else if (ls == -1) {
					return selector;
				}
				b = reader.readNotBlank();
				if (b == ')') {
					return selector;
				}
				throw new SyntaxException("条件选择器无法读取一个完整的条件",
						reader.getCurrentRow(), reader.getCurrentColumn());
			}
			throw new SyntaxException("条件选择器在必须以一个(开头", reader.getCurrentRow(),
					reader.getCurrentColumn());
		} catch (ReaderOverException e) {
			throw new SyntaxException("条件选择器无法读取一个完整的条件",
					reader.getCurrentRow(), reader.getCurrentColumn());
		}
	}

	private static int readcc(ReaderWrapper reader) throws IOException,
			ReaderOverException {
		char b = reader.readNotBlank();
		switch (b) {
		case '&':
			b = reader.read();
			if (b == '&')
				return 1;
			break;
		case '|':
			b = reader.read();
			if (b == '|')
				return 0;
			break;
		case ')':
			return -1;
		}
		throw new SyntaxException("读取逻辑运算符失败", reader.getCurrentRow(),
				reader.getCurrentColumn());
	}
}
